package com.sita.tingterest.activity;

import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sita.bike.R;
import com.sita.bike.rest.model.AudioMusic;
import com.sita.bike.support.GlobalContext;
import com.sita.tingterest.Implements.getCategoryJsonData;
import com.sita.tingterest.adapter.MusicListViewAdapter;
import com.sita.tingterest.fragment.EvalueFragment;
import com.sita.tingterest.fragment.ProgramFragment;
import com.sita.tingterest.pojo.Audio;
import com.sita.tingterest.pojo.Music;
import com.sita.tingterest.pojo.Pic;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;


public class MusicPlayGridViewActivity extends BaseActivity implements OnClickListener {
    public TextView tv_person;
    public ImageView imageView_music;
    public PullToRefreshListView music_ListView;
    public Intent intent;
    public int position;
    public String persion, img_url;
    public ImageButton imageButton_play;
    public ArrayList<Music> arrayListlist;
    public Context context;
    public static ArrayList<Music> musicList;
    public static ArrayList<Pic> picArrayList;
    public static ArrayList<AudioMusic> audioArrayList;
    private Music music;
    private Pic pic;
    private Audio audio;
    public String content;
    public String catId;
    public TextView tv_program, tv_evalue, tv_line_one, tv_line_two;
    public MusicListViewAdapter gridViewAdapter;
    public ProgramFragment programFragment;
    public FragmentManager manager;
    public EvalueFragment evalueFragment;
    public android.app.FragmentTransaction transation;
    public RelativeLayout mLayout;
    public SeekBar mSeekBar;
    public int mediaFileLengthInMilliseconds;
    public ImageView img_menu;
    public TextView tv_sharecount;
    public TextView tv_playcount;

    @Override
    public void onResume() {
        super.onResume();

        //isPause = false;

        // L.l("MY sr", "onResume()" + "  ..Fragment Recommends;");
    }

    @Override
    public void onPause() {
        allowUnbindService();
        //isPause = true;
        Log.i("MY sr", "onPause()" + "  ..Fragment Recommends;");
        super.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
        allowBindService();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play_grid_view);
        initView();
        initData();
        setTabSelection(0);
    }

    private void setTabSelection(int index) {
        clean();
        transation = manager.beginTransaction();
        hiden(transation);
        switch (index) {
            case 0:
                if (programFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    programFragment = new ProgramFragment();
                    transation.add(android.R.id.tabcontent, programFragment);
                    tv_line_one.setBackgroundColor(getResources().
                            getColor(android.R.color.holo_red_dark));

                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transation.show(programFragment);
                    tv_line_one.setBackgroundColor(getResources().
                            getColor(android.R.color.holo_red_dark));

                }
                break;
            case 1:
                if (evalueFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    evalueFragment = new EvalueFragment();
                    transation.add(android.R.id.tabcontent, evalueFragment);

                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transation.show(evalueFragment);
                }
                break;
        }
        transation.commit();
    }

    public void initView() {
        Intent intent = getIntent();
        catId = intent.getStringExtra("catId");
        imageButton_play = (ImageButton) findViewById(R.id.imageButton_play);
        tv_person = (TextView) findViewById(R.id.tv_persion);
        imageView_music = (ImageView) findViewById(R.id.image_title);
        music_ListView = (PullToRefreshListView)
                findViewById(R.id.music_listview);
        manager = getFragmentManager();
        programFragment = (ProgramFragment) manager.
                findFragmentById(R.id.program_fragment);
        music_ListView = (PullToRefreshListView) programFragment.getView().
                findViewById(R.id.music_listview);
        tv_program = (TextView) findViewById(R.id.tv_program);
        tv_evalue = (TextView) findViewById(R.id.tv_enval);
        tv_line_one = (TextView) findViewById(R.id.line_one);
        tv_line_two = (TextView) findViewById(R.id.line_two);
        mLayout = (RelativeLayout) findViewById(R.id.music_layout);
        mLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        mSeekBar = (SeekBar) findViewById(R.id.music_seekbar);
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) mSeekBar.getLayoutParams();
        p.leftMargin = (int) (GlobalContext.getGlobalContext().sScreenWidth * 0.1);
        p.rightMargin = (int) (GlobalContext.getGlobalContext().sScreenWidth * 0.1);

        img_menu = (ImageView) findViewById(R.id.img_back);
        tv_sharecount = (TextView) findViewById(R.id.tv_sharecount);
        tv_playcount = (TextView) findViewById(R.id.tv_playcount);
        img_menu.setOnClickListener(this);
        tv_evalue.setOnClickListener(this);
        tv_program.setOnClickListener(this);
    }

    public void initData() {
        DownLoadData downLoadData = (DownLoadData) new DownLoadData(new getCategoryJsonData() {
            @Override
            public void getCategoryData(String data) {
                arrayListlist = getJosonData(data);
                if (arrayListlist.size() <= 0) {
                    Toast.makeText(MusicPlayGridViewActivity.this, "该分类无播放内容", Toast.LENGTH_LONG).show();
                } else {
                    content = data;
                    mPlayService.updateMusicList(arrayListlist);
                    setGridView(arrayListlist);
                }

            }
        }).execute("http://www.sitayun.com:8080/tinterest/v1/resources/list");

        imageButton_play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // mPlayService.updateMusicList(getJosonData(content));
                imageButton_play.setImageResource(R.drawable.btn_pause);
                changePalyState();
            }
        });

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int dest = seekBar.getProgress();
                int mMax = mPlayService.getDuration();
                int sMax = seekBar.getMax();
                mPlayService.seek(mMax * dest / sMax);
            }
        });

    }

    public void changePalyState() {
        if (mPlayService.isPlaying()) {
            mPlayService.pausePlayer();
            imageButton_play.setImageResource(R.drawable.btn_music_play);
        } else {
            mPlayService.start();
            imageButton_play.setImageResource(android.R.drawable.ic_media_pause);
        }
    }

    public void clean() {
        tv_line_one.setBackgroundColor(getResources().getColor(android.R.color.white));
        tv_line_two.setBackgroundColor(getResources().getColor(android.R.color.white));
    }

    public void setGridView(ArrayList<Music> list) {
        gridViewAdapter = new MusicListViewAdapter(MusicPlayGridViewActivity.this, list);
        music_ListView.setMode(PullToRefreshBase.Mode.BOTH);
        //设置下拉刷新标题
        music_ListView.getLoadingLayoutProxy(true, false).setPullLabel("正在刷新。。");
        music_ListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新。。");
        music_ListView.getLoadingLayoutProxy(true, false).setReleaseLabel("刷新。。。");
        //设置上拉加载标题
        music_ListView.getLoadingLayoutProxy(false, true).setPullLabel("正在加载");
        music_ListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在努力加载");
        music_ListView.getLoadingLayoutProxy(false, true).setReleaseLabel("放手加载更多");
//        music_ListView.setAdapter(gridViewAdapter);
        ListView listView = music_ListView.getRefreshableView();
        listView.setAdapter(gridViewAdapter);
        initPlay();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AsyncTask<String, String, Bitmap> getImage = new GetImage().
                        execute(arrayListlist.get(position - 1).getPic().getUrl());
                tv_person.setText(arrayListlist.get(position - 1).getTitle());
                tv_playcount.setText("" + arrayListlist.get(position - 1).getPlayCount());
                tv_sharecount.setText("" + arrayListlist.get(position - 1).getVoteCount());
                mPlayService.play(position - 1);
                Log.i("MusicPlay", "play" + position);
                imageButton_play.setImageResource(android.R.drawable.ic_media_pause);
            }
        });

    }

    public void initPlay() {
        ImageLoader.getInstance().displayImage(arrayListlist.get(0).getPic().getUrl()
                , imageView_music);
        tv_person.setText(arrayListlist.get(0).getTitle());
        tv_playcount.setText("" + arrayListlist.get(0).getPlayCount());
        tv_sharecount.setText("" + arrayListlist.get(0).getVoteCount());
        mPlayService.play(0);
    }

    //解析json字符串
    private ArrayList<Music> getJosonData(String contents) {
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        String title = null;
        String picUrl = null;
        String audiolink = null;
        final String content;
        int playCount;
        int voteCount;
        try {
            jsonObject = new JSONObject(contents);
            jsonArray = jsonObject.getJSONArray("data");
            musicList = new ArrayList<Music>();
            picArrayList = new ArrayList<Pic>();
            audioArrayList = new ArrayList<AudioMusic>();
            for (int i = 0; i < jsonArray.length(); i++) {
                music = new Music();
                pic = new Pic();
                audio = new Audio();
                //获取title
                JSONObject jsonObjectContent = jsonArray.getJSONObject(i);
                title = jsonObjectContent.getString("title");
                playCount = jsonObjectContent.getInt("playcount");
                voteCount = jsonObjectContent.getInt("voteCount");
                music.setTitle(title);
                music.setPlayCount(playCount);
                music.setVoteCount(voteCount);
                musicList.add(music);
                //获取图片Url
                JSONArray jsonArrayPic = jsonObjectContent.getJSONArray("pic");
                JSONObject jsonObjectPic = jsonArrayPic.getJSONObject(0);
                picUrl = jsonObjectPic.getString("link");
                pic.setUrl(picUrl);
                music.setPic(pic);
                //获取AudioUrl
                JSONArray jsonArrayAudio = jsonObjectContent.getJSONArray("audio");
                JSONObject jsonObjectAudio = jsonArrayAudio.getJSONObject(0);
                audiolink = jsonObjectAudio.getString("link");
                audio.setUrl(audiolink);
                music.setAudio(audio);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return musicList;
    }

    public static String submitPostData(String url, String catId) {
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            //添加http头信息
            httppost.addHeader("Accept", "application/json"); //认证token
            httppost.addHeader("Content-Type", "application/json");
            //http post的json数据格式：  {"name": "your name","parentId": "id_of_parent"}
            JSONObject obj = new JSONObject();
            //obj.put("accountId","1");
            obj.put("catId", catId);
            httppost.setEntity(new StringEntity(obj.toString()));
            HttpResponse response;
            response = httpclient.execute(httppost);
            //检验状态码，如果成功接收数据
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
            Log.i("sd", "" + e);
        } catch (Exception e) {
            Log.i("ss", "" + e);
        }
        return result;
    }


    @Override
    protected void onChange(int position) {
        mSeekBar.setMax(mPlayService.getDuration());
    }

    @Override
    protected void onPublish(int progress) {
        mSeekBar.setProgress(progress);
    }

    @Override
    public void onClick(View v) {
        //clean();
        switch (v.getId()) {
            case R.id.tv_program:
                //setTabSelection(0);
                tv_line_one.setBackgroundColor(getResources().
                        getColor(android.R.color.holo_red_dark));
                break;
            case R.id.tv_enval:
                //setTabSelection(1);
                tv_line_two.setBackgroundColor(getResources().
                        getColor(android.R.color.holo_red_dark));
                break;
            case R.id.img_back:
                Intent intent = new Intent(MusicPlayGridViewActivity.this, TinterestActivity.class);
                startActivity(intent);
                break;
        }
    }

    //隐藏fragment
    public void hiden(android.app.FragmentTransaction fragmentTransaction) {
        if (fragmentTransaction != null) {
            fragmentTransaction.hide(programFragment);
        }
        if (evalueFragment != null) {
            fragmentTransaction.hide(evalueFragment);
        }
    }

    private class DownLoadData extends AsyncTask<String, Integer, String> {
        public getCategoryJsonData getCategoryData;

        public DownLoadData() {
        }

        public DownLoadData(getCategoryJsonData getCategoryData) {
            this.getCategoryData = getCategoryData;
        }

        @Override
        protected String doInBackground(String... params) {
            String content = submitPostData(params[0], catId);
            return content;
        }

        @Override
        protected void onPostExecute(String s) {
            getCategoryData.getCategoryData(s);
        }
    }

    //异步任务加载图片，将Bitmap转换成Drawable
    private class GetImage extends AsyncTask<String, String, Bitmap> {
        private Bitmap bmp;

        @Override
        protected Bitmap doInBackground(String... params) {


            try {
                InputStream in = new URL(params[0]).openStream();
                Log.i("MY TAG", "params[0]" + params[0]);
                bmp = BitmapFactory.decodeStream(in);
            } catch (Exception e) {

            }
            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            imageView_music.setImageBitmap(bitmap);
            //imageButton.setImageResource(android.R.drawable.ic_media_play);
        }
    }

}
